package com.xy.job.admin.core.notify

import com.xy.job.admin.core.InetAddressHolder
import com.xy.job.admin.domain.NotifyInstance
import com.xy.job.admin.enums.NotifyStatus
import com.xy.job.admin.repository.NotifyInstanceRepository
import com.xy.job.admin.service.NodeRegistryService
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.time.LocalDateTime

@Component
class NotifyExecutor(
    private var inetAddressHolder: InetAddressHolder,
    private var notifySenderFacade: NotifySenderFacade,
    private var nodeRegistryService: NodeRegistryService,
    private var notifyInstanceRepository: NotifyInstanceRepository,
) {

    @Scheduled(fixedDelay = 1000 * 60)
    fun execute() {
        if (!nodeRegistryService.isAdminMasterNode(inetAddressHolder.address)) {
            return
        }
        val pageable: Pageable = PageRequest.of(
            0, 100,
            Sort.by(NotifyInstance::createTime.name).ascending()
        )
        val notifyInstances = notifyInstanceRepository.findByCreateTimeGreaterThanAndNotifyStatus(
            startTime = LocalDateTime.now().minusHours(1),
            notifyStatus = NotifyStatus.WAIT,
            pageable = pageable
        )
        for (notifyInstance in notifyInstances) {
            val notifyStatus = notifySenderFacade.notify(notifyInstance)
            notifyInstance.notifyStatus = notifyStatus
        }
        notifyInstanceRepository.saveAll(notifyInstances)
    }
}